<?php  namespace App\Models;

use App\Cache\MRedis;
use App\Utils\CommonUtils;
use Log;
class Program extends BaseModel{
    
	//表明
	protected $table = 'program';
	//主键
	protected $primaryKey = 'id';
	
    //获取program实体
    public function getProgramObject($Obj=null){
        $data = array();
        $id;
        if($Obj){
            $id = $Obj['id'];
            $data['programId'] = $Obj['id'];
            $data['programName'] = $Obj['name'];
            $data['programUrl'] = $Obj['video_url'];
            $data['img'] = $Obj['img_broad']?$Obj['img_broad']:$Obj['img_tall'];
            $data['keywords'] = $Obj['keywords'];
            $data['directors'] = $Obj['directors'];
            $data['scriptwriter'] = $Obj['scriptwriter'];
            $data['actors'] = $Obj['actors'];
            $data['area'] = $Obj['area'];
            $data['type'] = $Obj['type'];
            $data['publishAt'] = date("Y",$Obj['publish_time']);
            $data['introduction'] = $Obj['introduction'];
            $data['isAttention'] = 0;
        }else{
            $id = $this->id;
            $data['programId'] = $this->id;
            $data['programName'] = $this->name;
            $data['programUrl'] = $this->video_url;
            $data['img'] = $this->img_broad?$this->img_broad:$this->img_tall;
            $data['keywords'] = $this->keywords;
            $data['directors'] = $this->directors;
            $data['scriptwriter'] = $this->scriptwriter;
            $data['actors'] = $this->actors;
            $data['area'] = $this->area;
            $data['type'] = $this->type;
            $data['publishAt'] = date("Y",$this->publish_time);
            $data['introduction'] = $this->introduction;
            $data['isAttention'] = 0;
        }
        if(env('OPENCACHE', '0')){
            $mRedis = new MRedis();
            $userId = $this->request->input('userId');
            if($userId){
                $ret = $mRedis->IsAttentionProgram($userId, $id);
                if($ret){
                    $data['isAttention'] = 1;
                }
            }
        }
        $pUid = with(new CommonUtils())->getUuid($id);
        $shareUrl = env('SHARE_URL','api.cbn.onairm.cn');
        if(FALSE === stripos($shareUrl, 'https://') && FALSE === stripos($shareUrl, 'http://')){
            $shareUrl = 'http://'.$shareUrl;
        }
        $data['shareUrl'] = $shareUrl.'/cbn/getShareProgramDetail?ty=web&programId='.$pUid;
        return $data;
    }
    //获取program详情
    public function getProgramDetail(){
        $programId = $this->request->input('programId');
        if(env('OPENCACHE', '0')){
            return $this->getRedisProgramObject($programId);
        }
        $program = Program::select('id','name','keywords','video_url','img_broad','img_tall','directors','scriptwriter','actors','area','publish_time','type','introduction','publish_time')
                ->where('id','=',$programId)
                ->first();
        if($program){
            if($program->is_delete == 1){ // 节目被删，同步时被忽略
                return ;
            }
            $program->request = $this->request;
            return $program->getProgramObject();
        }
    }
//    'from' => array('isNull' => FALSE, 'description'=>'视频来源 1 国广 2 PASS' ,'value' => array('1','2','3','4','5')),
////                        'uuid'=> array('isNull' => TRUE,'description'=>'第三方平台唯一id'),
//                        'programName'=> array('isNull' => FALSE,'description'=>'视频名称'),
//                        'keywords' => array('isNull' => FALSE, 'description'=>'多个关键词，逗号隔开', 'length' => array('min' => 2, 'max' => 200)),
//                        'img'=> array('isNull' => FALSE,'description'=>'视频截图或者海报'),
//                        'programUrl'=> array('isNull' => FALSE,'description'=>'内容'),//
//                        'directors'=> array('isNull' => FALSE,'description'=>'导演'),
//                        'scriptwriter'=> array('isNull' => FALSE,'description'=>'编剧'),
//                        'actors'=> array('isNull' => FALSE,'description'=>'主演'),
//                        'area'=> array('isNull' => FALSE,'description'=>'地区'),
//                        'type'=> array('isNull' => FALSE,'description'=>'类型'),
//                        'publishAt'=> array('isNull' => FALSE,'description'=>'发布时间'),
//                        'introduction'=> array('isNull' => FALSE,'description'=>'简介'),
//                        'curTime'=> array('isNull' => FALSE,'description'=>'当前播放时间'),
//                        'videoTime'=> array('isNull' => FALSE,'description'=>'总时长'),
    //同步视频节目
    public function syncProgram() {
        $userId = $this->request->input('userId');
        $uuid = $this->request->input('programId');
        $programName = $this->request->input('programName');
        $from = $this->request->input('from');
        $keywords = $this->request->input('keywords');
        $img = $this->request->input('img');
        $programUrl = $this->request->input('programUrl');
        $directors = $this->request->input('directors');
        $scriptwriter = $this->request->input('scriptwriter');
        $actors = $this->request->input('actors');
        $area = $this->request->input('area');
        $type = $this->request->input('type');
        $publishAt = $this->request->input('publishAt');
        $introduction = $this->request->input('introduction');
//        $curTime = $this->request->input('curTime');
//        $videoTime = $this->request->input('videoTime');
       
        $program = Program::select('id','name','keywords','video_url','img_broad','img_tall','directors','scriptwriter','actors','area','publish_time','type','introduction')
                ->where('from','=',$from)
                ->where('uid','=',$uuid)
                ->first();
        if($program){
            if($program->is_delete == 1){ // 节目被删，同步时被忽略
                $program->is_delete == 0;
            }
            if($programName){
                $program->name = $programName;
            }
            if($keywords){
                $program->keywords = $keywords;
            }
            if($programUrl){
                $program->video_url = $programUrl;
            }
            if($img){
                $program->img_broad = $img;
                $program->img_tall = $img;
            }
            if($directors){
                $program->directors = $directors;
            }
            if($scriptwriter){
                $program->scriptwriter = $scriptwriter;
            }
            if($actors){
                $program->actors = $actors;
            }
            if($area){
                $program->area = $area;
            }
            if($type){
                $program->type = $type;
            }
            if($publishAt){
                $program->publish_time = UNIX_TIMESTAMP($publishAt.'-01-01 00:00:00');
            }
            if($introduction){
                $program->introduction = $introduction;
            }
            $ret = $program->save();
            if(!$ret){
                return FALSE;
            }
            if(env('OPENCACHE', '0')){
                $mRedis = new MRedis();
                $ret = $mRedis->handleEntity('add', 'program', $program->id);
                if(!$ret){
                    return FALSE;
                }
            }
            return ['programId'=>$program->id];
        }
        $program = new Program();
        if($from){
                $program->from = $from;
        }
        if($uuid){
                $program->uid = $uuid;
        }
        if($programName){
            $program->name = $programName;
        }
        if($keywords){
            $program->keywords = $keywords;
        }
        if($programUrl){
            $program->video_url = $programUrl;
        }
        if($img){
            $program->img_broad = $img;
            $program->img_tall = $img;
        }
        if($directors){
            $program->directors = $directors;
        }
        if($scriptwriter){
            $program->scriptwriter = $scriptwriter;
        }
        if($actors){
            $program->actors = $actors;
        }
        if($area){
            $program->area = $area;
        }
        if($type){
            $program->type = $type;
        }
        if($publishAt){
            $program->publish_time = $publishAt;
        }
        if($introduction){
            $program->introduction = $introduction;
        }
        $ret = $program->save();
        if(!$ret){
            return FALSE;
        }
        if(env('OPENCACHE', '0')){
            $mRedis = new MRedis();
            $ret = $mRedis->handleEntity('add', 'program', $program->id);
            if(!$ret){
                return FALSE;
            }
        }
        return ['programId'=>$program->id];
    }
    //获取检索视频结果
    public function getSearchProgram(){
        $keywords = $this->request->input('keywords');
        $page = $this->request->input('page');
        $size = $this->request->input('size');
        $dataList = $this->select('id','name','keywords','video_url','img_broad','img_tall')
                ->where( function($query) use($keywords){
                    $keywords_arr = explode(',', $keywords);
                    foreach ($keywords_arr as $key => $value) {
                        $value = trim($value);
                        if($key === 0){
                            $query->where('name','like','%'.$value.'%')
                                ->orWhere('keywords','like','%'.$value.'%');
                        }else{
                            $query->orWhere('name','like','%'.$value.'%')
                                ->orWhere('keywords','like','%'.$value.'%');
                        }
                    }
                })
                ->where('is_delete','=',0)
                ->orderBy('publish_time','desc')
                ->skip($page*$size)
                ->take($size)
                ->get();
        $data = [];
        $data['data'] = [];
        $data['paging']['size'] = 0;
        if($dataList){
            foreach ($dataList as $val) {
                $val->request = $this->request;
                $data['data'][] = $val->getProgramObject();
            }
            if(is_array($data['data'])){
                $data['paging']['size'] = count($data['data']);
            }
        }
        return $data;
    }
    //获取用户关注的视频列表 此方法合并到getAttentionList里
    public function getUserProgramList(){
        $userId = $this->request->input('userId');
        $uId = $this->request->input('uId');
        $page = $this->request->input('page');
        $size = $this->request->input('size');
        if(env('OPENCACHE', '0')){
            $mRedis = new MRedis();
            //判断取列表
            $ids = $mRedis->getAttentionProgramIdsByUserId($uId, $page, $size);
            $size = count($ids);
            $data = [];
            $data['data'] = [];
            $data['paging']['size'] = 0;
            if($size > 0){
                foreach ($ids as $key => $val){
                    $temp = $this->getRedisProgramObject($key);
                    if($temp){
                        $data['data'][] = $temp;
                    }
                }
                if(is_array($data['data'])){
                    $data['paging']['size'] = $size;
                }
            }
            return $data;
            
            $pIdArr = array_keys($pros);//获取数组的Key
            
            $dataList = $this->select('program.id','program.name','program.keywords','program.video_url','program.img_broad','program.img_tall')
                    ->whereIn('program.id',$pIdArr)//视频
                    ->where('program.is_delete','=',0)
                    ->orderBy('program.publish_time','desc')
                    ->get();
            $data = array();
            $data['data'] = array();
            $data['paging']['size'] = 0;
            foreach ($dataList as $key => $val) {
                $val->request = $this->request;
                $data['data'][] = $val->getProgramObject();
            }
            if(isset($data['data'])){
                $data['paging']['size'] = $size;
            }
            return $data;
        }else{
            $dataList = $this->select('program.id','program.name','program.keywords','program.video_url','program.img_broad','program.img_tall')
                    ->join('attention','attention.item_id','=','program.id')//user_id,item_id,type
                    ->where('attention.user_id','=',$uId)
                    ->where('attention.type','=',2)//视频
                    ->where('program.is_delete','=',0)
                    ->where('attention.is_delete','=',0)
                    ->orderBy('program.publish_time','desc')
                    ->skip($page*$size)
                    ->take($size)
                    ->get();
            $data = [];
            $data['data'] = [];
            $data['paging']['size'] = 0;
            foreach ($dataList as $val) {
                $val->request = $this->request;
                $data['data'][] = $val->getProgramObject();
            }
            if(is_array($data['data'])){
                $data['paging']['size'] = count($data['data']);
            }
            return $data;
        }
    }
    
    //获取redis的实体数据
    public function getRedisProgramObject($Id){
        $mRedis = new MRedis();
        $Obj = $mRedis->getEntity('program', $Id);//获取实体
        if(!$Obj && $Id){
            Log::info("getRedisProgramObject:去数据库,id=".$Id);
            $ObjData = $this->select('program.id','program.name','program.keywords','program.video_url','program.img_broad','program.img_tall')
                    ->where('program.is_delete','=',0)
                    ->where('program.id','=',$Id)
                    ->first();
            if($ObjData){
                $ObjData->request = $this->request;
                return $ObjData->getProgramObject();
            }else{
                return FALSE;
            }
        }else{
//            $c = new Program($this->request);
            return $this->getProgramObject($Obj);
        }
    }
}